
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>书籍详情</title>
    <link rel="stylesheet" href="../../js/layui/css/layui.css">
    <script src="../../js/jquery-3.4.1.js"></script>
    <script src="../../js/layui/layui.all.js"></script>
    <style>
        .book-info {
            margin: 20px 0;
        }

        .book-info h2 {
            margin-bottom: 10px;
        }

        .book-info p {
            margin-bottom: 5px;
        }

        .reviews {
            margin-top: 20px;
        }

        .reviews h3 {
            margin-bottom: 10px;
        }

        .review-form {
            margin-top: 20px;
        }

        .review-form textarea {
            width: 100%;
            resize: none;
        }

        .borrow-button {
            margin-top: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
<%
    String bookId = request.getParameter("bookId");
%>
<div class="layui-container">
    <div class="layui-row">
        <div class="layui-col-md12">
            <div class="book-info">
                <h2 id="book-title">书籍标题</h2>
                <p><strong>作者：</strong><span id="book-author"></span></p>
                <p><strong>ISBN：</strong><span id="book-isbn"></span></p>
                <p><strong>出版社：</strong><span id="book-publisher"></span></p>
                <p><strong>出版日期：</strong><span id="book-publishDate"></span></p>
                <p><strong>库存量：</strong><span id="book-stockQuantity"></span></p>
                <p><strong>类型：</strong><span id="book-type"></span></p>
                <p><strong>介绍：</strong><span id="book-introduce"></span></p>
            </div>
            <div class="borrow-button">
                <button class="layui-btn layui-btn-normal" id="borrowBookBtn">借书</button>
            </div>
            <div class="review-form">
                <h3>发表书评</h3>
                <form class="layui-form" id="reviewForm">
                    <div class="layui-form-item">
                        <textarea name="comment" required lay-verify="required" placeholder="请输入书评内容"
                                  class="layui-textarea"></textarea>
                    </div>
                    <div class="layui-form-item">
                        <button class="layui-btn" type="submit">提交</button>
                    </div>
                </form>
            </div>
            <hr>
            <div class="reviews">
                <h3>书评区</h3>
                <ul id="review-list" class="layui-timeline">
                    <!-- 动态加载书评 -->
                </ul>
            </div>
        </div>
    </div>
</div>


<script>
    let bookId = <%= bookId %>;
    let bookData;
    let reviewList;
    let user;

    $(document).ready(function () {
        user = JSON.parse(sessionStorage.getItem('user'));


        $.ajax({
            url: '/bookDetailById',
            method: 'GET',
            data: {
                id: bookId
            },
            success: function (res) {
                bookData = res.data;
                loadBookDetail(bookData)
            },
            error: function () {
                console.log('服务器错误');
            }
        })

        /**
         * 填充书籍详情
         * @param book 信息数据
         */
        function loadBookDetail(book) {
            // 填充书籍信息
            $('#book-title').text(book.title);
            $('#book-author').text(book.author);
            $('#book-isbn').text(book.isbn);
            $('#book-publisher').text(book.publisher);
            $('#book-publishDate').text(book.publish_date);
            $('#book-stockQuantity').text(book.stock_quantity);
            $('#book-type').text(book.type);
            $('#book-introduce').text(book.introduce);
            // 填充书评
            reviewList = $('#review-list');
            book.reviews.forEach(function (review) {
                var li = $('<li class="layui-timeline-item">');
                var content = '<i class="layui-icon layui-timeline-axis">&#xe63f;</i>';
                content += '<div class="layui-timeline-content layui-text">';
                content += '<h3 class="layui-timeline-title">' + review.review_date + '</h3>';
                content += '<p>' + review.user_name + ': ' + review.comment + '</p>';
                content += '</div>';
                li.html(content);
                reviewList.append(li);
            });
        }

        /**
         * 提交书评
         */
        $('#reviewForm').on('submit', function (e) {
            e.preventDefault();
            if (checkSession()){
                let comment = $('[name="comment"]').val();
                if (comment) {
                    $.ajax({
                        url: '/user/addBookReview',
                        method: 'POST',
                        data: {
                            bookId: bookId,
                            comment: comment,
                            rating: 5,// 假设评分是5
                            userId: user.userId
                        },
                        success: function (res) {
                            if (comment) {
                                let review = {
                                    userId: user.userId, // 模拟用户ID
                                    bookId: bookId,
                                    rating: 5, // 模拟评分
                                    comment: comment,
                                    review_date: new Date().toISOString().split('T')[0],
                                    user_name: user.username
                                };
                                bookData.reviews.push(review);
                                let li = $('<li class="layui-timeline-item">');
                                let content = '<i class="layui-icon layui-timeline-axis">&#xe63f;</i>';
                                content += '<div class="layui-timeline-content layui-text">';
                                content += '<h3 class="layui-timeline-title">' + review.review_date + '</h3>';
                                content += '<p>' + review.user_name + ': ' + review.comment + '</p>';
                                content += '</div>';
                                li.html(content);
                                reviewList.append(li);
                                $('[name="comment"]').val('');
                            }
                        },
                        error: function () {
                            console.log('服务器错误');
                        }
                    })
                }else {
                    layer.msg('请先输入书评内容', {icon: 2});
                }
            }
        });

        /**
         * 处理借书
         */
        $('#borrowBookBtn').on('click', function () {
            if (checkSession()){
                layer.confirm('确定要借这本书吗？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    // 模拟访问后端
                    $.ajax({
                        url: '/user/addBorrowRecord',
                        method: 'POST',
                        data: {
                            bookId: bookId,
                            userId: user.userId
                        },
                        success: function (res) {
                            if (res.code === 200) {
                                layer.msg(res.msg, {icon: 1});
                                $('#borrowBookBtn').hide();
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        },
                        error: function () {
                            console.log('服务器错误');
                        }
                    })
                });
            }
        });

        /**
         * 检查 session 并跳转到登录页面
         * @returns {boolean}
         */
        function checkSession() {
            if (!user) {
                layui.layer.msg('请先登录', {icon: 2});
                return false;
            }
            return true;
        }
    })

</script>

</body>
</html>
